package com.nineclock.auth.config;

import com.nineclock.auth.exception.NcDefaultWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;

@Configuration
@EnableAuthorizationServer  //开启 认证 ， 作为认证服务器
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
  
    //配置客户端的详情信息
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        clients.inMemory()
//                //配置客户端的标识
//                .withClient("nc_client_app")
//                .secret(passwordEncoder.encode("123456"))
//                .scopes("all")
//                .redirectUris("http://localhost") //重定向的路径
//                .authorizedGrantTypes("authorization_code","password") //认证模式
//                .and()
//                .withClient("nc_client_pc")
//                .secret(passwordEncoder.encode("123456"))
//                .scopes("all")
//                .redirectUris("http://localhost")
//                .authorizedGrantTypes("authorization_code","password");
        clients.withClientDetails(detailsService());
    }

    @Autowired
    DataSource dataSource;

    @Bean
    public JdbcClientDetailsService detailsService(){
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource);
        return jdbcClientDetailsService;
    }
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll") //tokenkey当使用JwtToken且使用非对称加密时，资源服务用于获取公钥而开放的，这里指这个 endpoint(/oauth/token )完全公开
                .checkTokenAccess("permitAll") //checkToken这个endpoint(/oauth/authorize) 完全公开
                .allowFormAuthenticationForClients(); //允许表单认证(密码/授权码模式认证)
    }

    @Autowired
    ClientDetailsService clientDetailsService;
    @Autowired
    TokenStore tokenStore;

    @Autowired
    JwtAccessTokenConverter tokenConverter;

    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices() ;
        defaultTokenServices.setClientDetailsService(clientDetailsService); // 设置客户端详情服务
        defaultTokenServices.setTokenStore(tokenStore); //token存储对象
        defaultTokenServices.setAccessTokenValiditySeconds(12 * 60 * 60);  // 访问token的有效期
        defaultTokenServices.setRefreshTokenValiditySeconds(30 * 24 * 60 * 60); // 刷新token的有效期
        // token增强对象
        defaultTokenServices.setTokenEnhancer(tokenConverter);
        //支持刷新token
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

    @Autowired
    AuthenticationManager authenticationManager;
    
	
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.exceptionTranslator(new NcDefaultWebResponseExceptionTranslator())
                .tokenServices(tokenServices()) //对token的管理
                 .authenticationManager(authenticationManager)
                 .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }
}